<template>
  <div>
    <!-- 添加或修改资产清单表对话框 -->
    <el-dialog ref="editDialog" v-model="openFlag" :title="title" width="50%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="108px" class="dialog-form-two">
        <el-row>
          <el-col :span="12">
            <el-form-item label="编码" prop="number">
              <el-input disabled v-model="form.number" placeholder="自动生成" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="名称" prop="name">
              <el-input v-model.trim="form.name" placeholder="请输入" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="资产分类" prop="categoryId">
              <category-select v-model="form.categoryId"></category-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="品牌" prop="brand">
              <el-input v-model.trim="form.brand" placeholder="请输入品牌" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="规格型号" prop="model">
              <el-input v-model.trim="form.model" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单价" prop="price">
              <el-input v-model.trim="form.price" placeholder="请输入" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="计量单位" prop="unit">
              <el-input v-model.trim="form.unit" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="限领数量" prop="useLimit">
              <el-input-number v-model="form.useLimit" placeholder="请输入" min="0" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="安全库存上限" prop="inventoryMax">
              <el-input-number v-model="form.inventoryMax" placeholder="请输入" min="0" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="安全库存下限" prop="inventoryMin">
              <el-input-number v-model="form.inventoryMin" placeholder="请输入" min="0" />
            </el-form-item>
          </el-col>
        </el-row>


        <el-row>

          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input type="textarea" v-model="form.remark"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="图片" prop="imgUrl">
              <el-upload class="avatar-uploader" :headers="headersObj" :action="uploadUrl" :show-file-list="false"
                :on-success="handleUploadSuccess" :before-upload="beforeUpload">
                <img alt="" v-if="form.imgUrl" :src="imgUrl" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon">
                  <Plus />
                </el-icon>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>

import { addAssetItem, updateAssetItem, getAssetItem } from "./api.js";
import UserSelect from "@/components/User/UserSelect.vue";
import CategorySelect from "@/components/Asset/CategorySelect.vue";
import WarehouseSelect from "@/components/Warehouse/WarehouseSelect.vue";
import { getToken } from '@/utils/auth'

export default {
  name: "AssetItemEdit",
  components: {WarehouseSelect, UserSelect, CategorySelect},
  props: {
  },
  data() {
    return {
      openFlag: false,
      currentRow: null,
      isEdit: false,
      uploadUrl: import.meta.env.VITE_APP_BASE_API + '/uploadImg',
      // 表单参数
      form: {
        id: null,
        number: null,
        name: null,
        categoryId: null,
        categoryName: null,
        rfid: null,
        brand: null,
        model: null,
        price: null,
        imgUrl: null,
        warehouseId: null
      },
      // 表单校验
      rules: {
        categoryId: [
          { required: true, message: "请选择资产分类", trigger: "change" }
        ],
        name: [
          { required: true, message: "名称不能为空", trigger: "blur" },
          { max: 50, message: "名称不得超过50个字符", trigger: "blur" }
        ],
        brand: [
          { required: true, message: "品牌不能为空", trigger: "blur" },
          { max: 20, message: "品牌名称不能超过50个字符", trigger: "blur" }
        ],
        model: [
          { required: true, message: "规格型号不能为空", trigger: "blur" },
          { max: 20, message: "规格型号不能超过20个字符", trigger: "blur" }
        ], 
        price:[
          { required: true, message: "单价不能为空", trigger: "blur" },
          { pattern: /^\d+(\.\d+)?$/, message: '请输入有效的单价' }
        ],
        unit: [
          { required: true, message: "计量单位不能为空", trigger: "blur" },
          { max: 50, message: "计量单位不能超过50个字符", trigger: "blur" }
        ],
      
        imgUrl: [
          { required: true, message: "请上传图片", trigger: "change" }
        ]
      }

    }
  },
  
  computed: {
    title() {
      return this.isEdit ? "编辑" : "新增"
    },
    headersObj() {
      return {
        'Authorization': 'Bearer ' + getToken()
      }
    },
    imgUrl() {
      return import.meta.env.VITE_APP_BASE_API + this.form.imgUrl;
    }
    
  },
  methods: {
    open(currentRow) {
      this.openFlag = true;
      this.reset();
      if (currentRow) {
        this.isEdit = true;
        this.currentRow = currentRow;
        this.handleUpdate(currentRow);
      } else {
        this.isEdit = false;
        this.currentRow = null;
      }
    },
    // 取消按钮
    cancel() {
      this.reset();
      this.openFlag = false;
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        number: null,
        name: null,
        categoryId: null,
        categoryName: null,
        rfid: null,
        brand: null,
        model: null,
        buyWay: null,
        buyTime: null,
        buyPrice: null,
        adminId: null,
        pricel:null
      };
    },
    // 打开选择分类的窗口
    openChooseCategory() {
      this.$refs.chooseCategoryDialog.open();
    },
    onSubChooseCategory(cate) {
      this.form.categoryId = cate.id;
      this.form.categoryName = cate.name;
      console.log('form', this.form);
      
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      
      const id = row.id || this.ids
      getAssetItem(id).then(response => {
        this.form = response;
      });
    },
    beforeUpload(rawFile) {
      if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
        this.$modal.alert('请上传图片格式!');
        return false
      } else if (rawFile.size / 1024 / 1024 > 2) {
        this.$modal.alert('图片不能超过2M!');
        return false
      }
      return true
    },
    handleUploadSuccess(response, uploadFile) {
      this.form.imgUrl = response.fileName;
    },
    /** 提交按钮 */
    submitForm: function () {

      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.isEdit) {
            updateAssetItem(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.openFlag = false;
              this.$emit("sub");
            });
          } else {
            addAssetItem(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.openFlag = false;
              this.$emit("sub");
            })
          }

        }
      });
    },
    
  },
  watch: {
    
  }
}


</script>

<style scoped lang="scss">
.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

.avatar-uploader {
  width: 80px;
  height: 80px;
  background-color: #fff;
  border-radius: 2px;
  border: 1px dashed #d9dbde;
  flex-shrink: 0;
  overflow: hidden;
  cursor: pointer;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 80px;
  height: 80px;
  text-align: center;
}

.avatar {
  width: 80px;
  height: 80px;
}

</style>
